<?php

namespace App\Http\Controllers\Port;


use App\Http\Controllers\ScoreRuleController;
use App\Models\BindLog;
use App\Models\UserInfo;
use App\Validate\LibInfoValidate;
use App\Models\UserLibraryInfo;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 图书馆对接接口信息
 */
class LibInfoController extends CommonController
{
    public $libapiObj = null;
    public $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->validate = new LibInfoValidate();
        $this->libapiObj = $this->getLibApiObj();
    }


    /**
     * 绑定读者证  或密码错误重新登录
     * @param $authorrization ：用户 token
     * @param account 读者证号
     * @param password 读者证密码
     */
    public function bingReaderId()
    {
        $account = $this->request->account;
        $password = $this->request->password;

        $user_id = $this->request->user_info['id'];

        //增加验证场景进行验证
        if (!$this->validate->scene('bing_reader')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否绑定了读者证
        $userInfoModel = new UserInfo();
        $user_info = $userInfoModel->where('id', $user_id)->first();
        //因为可能是密码错误。这个不判断
        // if (!empty($user_info['account_id'])) {
        //     return $this->returnApi(202, "您已绑定其他读者证，请勿重复绑定");
        // }

        $res = $this->libapiObj->login($account, $password);

        if ($res['code'] === 200) {
            //登录成功
            DB::beginTransaction();
            try {
                $account = $res['content']['account']; //重新赋值账号，因为有可能是身份证登录的

                $userLibraryInfoModel = new UserLibraryInfo();
                $result = $userLibraryInfoModel->where('account', $account)->first();

                $first_bind = $result; //用这个判断是否已经绑定过

                //获取读者证号信息
                $readerInfo = $this->libapiObj->getReaderInfo($account);
                if ($readerInfo['code'] === 200) {
                    $res['content']['cash'] = $readerInfo['content']['readerFinInfo']['depositYuan'];
                    $res['content']['diff_money'] = $readerInfo['content']['readerFinInfo']['arrearsYuan'];
                }

                if ($result) {
                    //判断此读者证是否被其他用户绑定
                    $isBindAccount = $userLibraryInfoModel->isBindAccount($result->id, $user_id);
                    if ($isBindAccount !== true) {
                        throw new \Exception($isBindAccount, 2002);
                    }

                    $res['content']['password'] = $password;
                    $qr_url = $userLibraryInfoModel->change($res['content'], $result);
                    $account_id = $result->id;
                } else {
                    $res['content']['password'] = $password;
                    $qr_url = $userLibraryInfoModel->change($res['content']);
                    $account_id = $userLibraryInfoModel->id;
                }

                //绑定在用户信息里面
                if (empty($user_info['account_id'])) {
                    //修改读者证号二维码
                    $userInfoModel->where('id', $user_id)->update([
                        'account_id' => $account_id,
                        'qr_url' => $qr_url,
                        'bind_time' => date('Y-m-d H:i:s')
                    ]);

                    //添加绑定日志
                    $bindLogModel = new BindLog();
                    $bindLogModel->add([
                        'user_id' => $user_id,
                        'account' => $account,
                        'password' => $password,
                        'state' => 1,
                    ]);
                } elseif ($user_info['account_id'] != $account_id) {
                    throw new Exception('您已绑定其他读者证号，请勿重复绑定！', 2002);
                }

                //是否第一次绑定读者证
                if (config('other.is_need_score') === true && empty($first_bind)) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus(1, $user_id, $account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);

                    if ($score_status['code'] == 200) {
                        $system_id = $this->systemAdd($score_status['score_info']['type_name'], $user_id, $account_id, 1, 0, $score_status['score_info']['intro']);
                        $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, $system_id); //添加积分消息
                    }

                    $invite_user_info = $userInfoModel->where('id', $user_id)->first();
                    //增加邀请人的积分
                    if (!empty($invite_user_info['invite_user_id']) || !empty($invite_user_info['invite_account_id'])) {
                        $invite_account_id = $invite_user_info['invite_account_id'];
                        //从新获取读者证id
                        if (empty($invite_account_id)) {
                            $invite_account_id = $userInfoModel->where('id', $invite_user_info['invite_user_id'])->value('account_id');
                        }
                        if (!empty($invite_account_id)) {
                            $score_status = $scoreRuleObj->checkScoreStatus(3, $invite_user_info['invite_user_id'], $invite_account_id);
                            if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);

                            if ($score_status['code'] == 200) {
                                $system_id = $this->systemAdd($score_status['score_info']['type_name'], $invite_user_info['invite_user_id'], $invite_user_info['invite_account_id'], 12, 0, $score_status['score_info']['intro']);
                                $scoreRuleObj->scoreChange($score_status, $invite_user_info['invite_user_id'], $invite_user_info['invite_account_id'], $system_id); //添加积分消息
                            }
                        }
                    }
                }
                DB::commit();
                return $this->returnApi(200, '绑定成功', true);
            } catch (\Exception $e) {
                dump($e->getMessage());
                dump($e->getFile());
                dump($e->getLine());die;
                $msg = $e->getCode() == 2002 ? $e->getMessage() : '绑定失败';
                DB::rollBack();
                return $this->returnApi(202, $msg);
            }
        } else {
            return $this->returnApi(207, $res['msg'] ? $res['msg']  : "登录失败,读者证号或密码不正确");
        }
    }

    /**
     * 解除绑定读者证
     * @param @param $authorrization ：用户 token
     */
    public function unBindReaderId()
    {
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $res = UserInfo::find($user_id);
        if (empty($res)) {
            return $this->returnApi(202, '信息获取失败');
        }
        if (empty($res['account_id'])) {
            return $this->returnApi(202, '网络错误');
        }

        DB::beginTransaction();
        try {
            $res->account_id = null;
            $res->qr_url = null;
            $res->bind_time = date('Y-m-d H:i:s');
            $res->save();

            BindLog::where('user_id', $user_id)->where('state', 1)->update(['state' => 2, 'change_time' => date('Y-m-d H:i:s')]);

            //修改掉之前的二维码
            // if ($res->qr_url) {
            //     @unlink(config('other.img_addr') . $res->qr_url);
            // }

            DB::commit();
            return $this->returnApi(200, '解除绑定成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '解除绑定失败');
        }
    }

    /**
     * 修改读者证密码
     * @param @param $authorrization ：用户 token  必须要绑定读者证
     * @param $old_password  读者旧密码
     * @param $new_password  读者新密码
     */
    public function changePwd()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change_password')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $old_password = $this->request->old_password;
        $new_password = $this->request->new_password;

        $account_info = UserLibraryInfo::select('id', 'account')->find($account_id);
        if (empty($account_info)) {
            return $this->returnApi(201, "网错错误");
        }
        //验证旧密码是否正确,验证通过后修改密码
        $res = $this->libapiObj->updateReaderPassword($account_info->account, $old_password, $new_password);

        if ($res['code'] === 200) {
            return $this->returnApi(200, "修改成功", true);
        } else {
            return $this->returnApi(202, $res['msg']);
        }
    }
}
